package com.pindao.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.pindao.data.common.Result;
import com.pindao.data.domain.RequestEvent;
import com.pindao.data.service.ApiDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service
@Slf4j
public class ApiDataEsServiceImpl implements ApiDataService {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${apidata.index}")
    private String index;

    @Value("${kafka.topic}")
    private String topic;

    @Value("${spring.profiles.active}")
    private String profiles;

    private String[] urls = {"/user/base-userinfo",
            "/home/api/otherActives",
            "/home/api/store/location/v2",
            "/product/api/get/store/menu/v2",
            "/product/api/get/item/detail/v3",
            "/cart/maintainNormalCart",
            "/order/preview",
            "/order/createGeneral",
            "/pay/pullCashier",
            "/pay/payCreate"};

    @Override
    public Result saveReqData(HttpServletRequest request, Map<String, Object> paramsMap) throws Exception {

        String id = UUID.randomUUID().toString().replace("-", "");

        RequestEvent event = new RequestEvent();
        event.setId(id);
        event.setIndex(index);

        //从request获取header通过getHeaderNames获得所有头名字的Enumeration集合
        String headName;
        StringBuilder header = new StringBuilder();
        Enumeration<String> headNames = request.getHeaderNames();
        while (headNames.hasMoreElements()) {
            headName = headNames.nextElement();
            header.append(headName).append(": ").append(request.getHeader(headName)).append(System.getProperty("line" +
                    ".separator"));
            if ("pd-host".equalsIgnoreCase(headName)) {
                event.setDomain(request.getHeader(headName));
            }
        }
        event.setHeader(header.toString());

        //其他都从paramMap获取

        //req_body
        if (paramsMap.containsKey("req_body")) {
            event.setReq_body(paramsMap.get("req_body").toString());
        } else {
            event.setReq_body("");
        }

        //req_uri
        if (paramsMap.containsKey("req_uri")) {
            event.setReq_uri(paramsMap.get("req_uri").toString());
        } else {
            event.setReq_uri("");
        }

        //resp_body
        if (paramsMap.containsKey("resp_body")) {
            event.setResp_body(paramsMap.get("resp_body").toString());
        } else {
            event.setResp_body("");
        }

        //req_method
        if (paramsMap.containsKey("req_method")) {
            event.setReq_method(paramsMap.get("req_method").toString());
        } else {
            event.setReq_method("");
        }

        //req_param
        if (paramsMap.containsKey("req_param")) {
            event.setReq_param(paramsMap.get("req_param").toString());
        } else {
            event.setReq_param("");
        }
        if ("prod".equals(profiles)) {
            //if (contains(urls, event.getReq_uri()) && random()) {
                String message = JSON.toJSONString(event);
                kafkaTemplate.send(topic, message);
            //}
        } else {
            String message = JSON.toJSONString(event);
            kafkaTemplate.send(topic, message);
        }

        return Result.success();
    }


    private boolean contains(String[] arr, String targetValue) {
        Set<String> set = new HashSet<String>(Arrays.asList(arr));
        return set.contains(targetValue);
    }


    private boolean random() {
        int max = 10;
        int min = 1;
        int ran2 = (int) (Math.random() * (max - min) + min);
        return ran2 == 5;
    }

}
